package com.sp.scmdb.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sp.scmdb.bean.ReaderBean;
import com.sp.scmdb.bean.SecurityTrainingBean;
import com.sp.scmdb.bean.UserBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.common.action.BaseAction;
import com.sp.scmdb.entity.LabelReadingMachine;
import com.sp.scmdb.entity.Map;
import com.sp.scmdb.entity.Reader_Alarm;
import com.sp.scmdb.entity.SecurityTraining;
import com.sp.scmdb.exception.ExcelException;
import com.sp.scmdb.service.ExportExcelService;
import com.sp.scmdb.service.MapService;
import com.sp.scmdb.service.ReaderService;
import com.sp.scmdb.service.SecurityTrainingService;

@Controller("readerAction")
@Scope("prototype")
public class ReaderAction extends BaseAction<ReaderBean> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Log log = LogFactory.getLog(ReaderAction.class);
	private ReaderService readerService;
	private SecurityTrainingService securityTrainingService;
	private MapService mapService;
	private ExportExcelService exportExcelService;
	private InputStream excelStream;
	private String fileName;
	private List<String> maps;


	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

	public void setMaps(List<String> maps) {
		this.maps = maps;
	}

	public List<String> getMaps() {
		return maps;
	}
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	@Autowired	
	public void setExportExcelService(ExportExcelService exportExcelService) {
		this.exportExcelService = exportExcelService;
	}

	@Autowired
	public void setMapService(MapService mapService) {
		this.mapService = mapService;
	}

	@Autowired
	public void setReaderService(ReaderService readerService) {
		this.readerService = readerService;
	}
	@Autowired
	public void setSecurityTrainingService(
			SecurityTrainingService securityTrainingService) {
		this.securityTrainingService = securityTrainingService;
	}

	@SuppressWarnings("unchecked")
	public String findAll() {
		try {
			ReaderBean readerBean = null;
			if (StringUtils.isNotEmpty(pageName)) {
				readerBean = (ReaderBean) session.get("readerBean");
			}else{
				entity.setPageNo(1);
			}
			setEntity(readerService.queryReaderAll(entity, readerBean));
			session.put("readerBean", entity);		
			session.put("readerStatus", CommonParamter.TypeCommon.getReaderState());
			session.put("readerType", CommonParamter.TypeCommon.getReaderType());
			this.button("Super.Popup(5,'添加','/SCMDB/readerAction!newReader.action','',466,376)",
					"Super.editData('/SCMDB/readerAction!findReader.action?id=',466,376)",
					"Super.delData('/SCMDB/readerAction!delReader.action?pId=')");
			return SUCCESS;
		} catch (Exception e) {
			log.error("get map and reader failed! reason:" + e.getMessage());
			return "fail";
		}
	}
	
	public String newReader(){
		List<SecurityTrainingBean> trainingList = securityTrainingService.getListSecurityTraining(null);
		request.setAttribute("trainingList", trainingList);
		return "newSucc";
	}
	public String findReader() {
		try {
			List<SecurityTrainingBean> trainingList = securityTrainingService.getListSecurityTraining(null);
			request.setAttribute("trainingList", trainingList);
			String pId = request.getParameter("id");
			entity = readerService.queryReaderByID(pId);
			return "editSucc";
		} catch (Exception e) {
			log.error("edit reader failed! reason:" + e.getMessage());
			return "fail";
		}
	}
	
	public ReaderAction()
	{
		setMaps(new ArrayList<String>());
		getMaps().add("地下监控图");
		getMaps().add("地上监控图");
		getMaps().add("工程示意图");
	}

	public String editReader() {
		try {
			UserBean user = (UserBean) session.get("user");
			SecurityTrainingBean securityTrainingBean = securityTrainingService.getSecurityTraining(securityTrainingId);
			entity.setSecurityTraining(securityTrainingBean);
			String result = readerService.editReader(entity, user);
			if (result.equals(CommonParamter.CHECK_FLG)) {
				messageSession(result, "区域已经使用");
			} else {
				messageSession(result, "读卡器");
			}
			return "commitSucc";
		} catch (Exception e) {
			log.error("edit reader failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	public String delReader() {
		String flg = null;
		try {
			UserBean user = (UserBean) session.get("user");
			String pId = request.getParameter("pId");
			if (StringUtils.isNotEmpty(pId)) {
				String[] arr = pId.split(",");
				flg = readerService.delReader(arr, user);
			}
			if (flg.equals(CommonParamter.CHECK_FLG)) {
				messageSession(flg, "区域已经使用");
			} else {
				messageSession(flg, "读卡器");
			}
			log.info("delete suncce");
		} catch (Exception e) {
			log.error("delete fail" + e.getMessage());
		}
		return "commitSucc";
	}
	private String securityTrainingId;

	public void setSecurityTrainingId(String securityTrainingId) {
		this.securityTrainingId = securityTrainingId;
	}
	public String addReader() {
		try {
			UserBean user = (UserBean) session.get("user");
			SecurityTrainingBean securityTrainingBean = securityTrainingService.getSecurityTraining(securityTrainingId);
			entity.setSecurityTraining(securityTrainingBean);
			String result = readerService.newReader(entity, user);
			messageSession(result, "读卡器");
			return "commitSucc";
		} catch (Exception e) {
			log.error("add reader failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	public String initRead() {
		try {
			int mapID = Integer.parseInt((String)request.getAttribute("mapID"));
			List<LabelReadingMachine> listRead = readerService.queryAll();
			List<LabelReadingMachine> finalListRead = new ArrayList<LabelReadingMachine>();
			for(LabelReadingMachine read : listRead)
			{
				  if(read.getMapID() == mapID)
				  {
					  finalListRead.add(read);
				  }
			}
			

			request.setAttribute("listRead", finalListRead);
//			List<Map> listMap = mapService.queryIsUsed();
//			request.setAttribute("listMap", listMap);
			

			
			
			return "setSucc";
		} catch (Exception e) {
			log.error("init reader failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	public String resetRead() {
		try {
			UserBean user = (UserBean) session.get("user");
			readerService.editReaderPosition(entity, user);
			return SUCCESS;
		} catch (Exception e) {
			log.error("reset reader failed! reason:" + e.getMessage());
			return SUCCESS;
		}
	}

	public String readerList() {
		try {
			String lrmID = request.getParameter("lrmID");
			String startTime = request.getParameter("startTime");
			String endTime = request.getParameter("endTime");
			StringBuffer sql = new StringBuffer();
			sql.append("from Reader_Alarm where 1=1 ");
			if(lrmID!=null){
				sql.append("and lrmID="+lrmID+" ");
			}
			if(startTime!=null && endTime!=null){
				sql.append("and startTime>'"+startTime+" 00:00:00' and startTime<'"+endTime+" 00:00:00' order by lrmID");
			}
			List<Reader_Alarm> readerList =  readerService.readerList(sql.toString());
			request.setAttribute("readerList", readerList);
			return "readerList";
		} catch (Exception e) {
			log.error("reset reader failed! reason:" + e.getMessage());
			return SUCCESS;
		}
	}

	public String downLoadExcel() {
		try {
			Workbook wb = new HSSFWorkbook();
			ReaderBean readerBean = (ReaderBean) session.get("readerBean");
			String tableName = "读卡器信息列表";
			wb = exportExcelService.createReaderExcel(readerBean,tableName);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			tableName = new String("读卡器信息列表".getBytes(), "ISO-8859-1");
			this.fileName = tableName + ".xls";
			wb.write(out);
			excelStream = new ByteArrayInputStream(out.toByteArray());
			out.flush();
			out.close();
			return "outExcel";
		} catch (ExcelException excel) {
			log.error("create excel failed! reason:" + excel.getMessage());
			return "fail";
		} catch (Exception e) {
			log.error("excel failed! reason:" + e.getMessage());
			return "fail";
		}
	}
	/**
	 * 查询上传数据
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String findUpload() {
		try {
			ReaderBean readerBean = null;
			if (StringUtils.isNotEmpty(pageName)) {
				readerBean = (ReaderBean) session.get("readerBean");
			}else{
				entity.setPageNo(1);
			}
			setEntity(readerService.queryReaderAll(entity, readerBean));
			session.put("readerBean", entity);
			session.put("readerStatus", CommonParamter.TypeCommon.getReaderState());
			session.put("readerType", CommonParamter.TypeCommon.getReaderType());
			return "findUpload";
		} catch (Exception e) {
			log.error("get map and reader failed! reason:" + e.getMessage());
			return "fail";
		}
	}
	public String upload() {
		try{
			String id = request.getParameter("id");
			String result = readerService.upload(id);
			if (result.equals("timeOut")) {
				messageSession(CommonParamter.CHECK_FLG, "连接超时");
			} else if (result.equals("success")) {
				messageSession(CommonParamter.CHECK_SUCCESS, "上传数据");
			} else if (result.equals(CommonParamter.CHECK_FAIL)) {
				messageSession(CommonParamter.CHECK_FAIL, "上传数据");
			}else{
				messageSession(CommonParamter.CHECK_FLG,result);
			}
		} catch (Exception e) {
			log.error("find leadership error!reason:" + e.getMessage());
			return "fail";
		}
	return "upload";
	}
}
